"""
修复异步函数中COS配置的使用方式
将原来的静态导入改为动态获取
"""

import io
import traceback
import datetime
from flask import current_app


def async_save_record(file_content, ocr_text, search_results, current_user,
                      device_info, ip_address, recognition_result, success_rate, tenant_id):
    """
    异步上传图片到COS，保存识别记录到数据库（带 Flask 上下文）
    修复版本：在运行时获取COS配置
    """
    import gc
    import uuid
    import json
    from app.apis.recognition_api import get_mobile_model
    from app.core.extensions import db
    from app.models.recognition_record import RecognitionRecord
    from app.models.user import User
    from app.services.doubao import save_result_to_json
    
    # ✅ 修复：在运行时获取COS配置，传入tenant_id
    from app.utils.cos_utils import get_cos_client

    try:
        # 生成唯一文件名 + 日期目录
        now = datetime.datetime.now()
        date_folder = now.strftime('%Y%m%d')
        unique_filename = f"{date_folder}/{now.strftime('%H%M%S')}_{uuid.uuid4().hex}.jpg"

        # ✅ 修复：动态获取COS客户端，传入tenant_id
        cos_client, bucket, region = get_cos_client(tenant_id=tenant_id)

        # 上传COS
        photo_url = None
        try:
            ret = cos_client.put_object(
                Bucket=bucket,  # ✅ 使用动态获取的bucket
                Body=io.BytesIO(file_content),
                Key=unique_filename,
                EnableMD5=True
            )
            if ret.get('ETag'):
                photo_url = f"https://{bucket}.cos.{region}.myqcloud.com/{unique_filename}"
            else:
                current_app.logger.warning("COS上传失败，未返回ETag")
        except Exception as e:
            current_app.logger.error(f"COS上传异常: {str(e)}")

        del file_content
        gc.collect()

        # 设备信息处理
        device_info = get_mobile_model(device_info)
        ip_address = ip_address[:45] if ip_address else ''
        username = current_user.nick_name
        safe_ocr_text = ocr_text[:100] + '...' if len(ocr_text) > 250 else ocr_text

        # 保存记录
        record = RecognitionRecord(
            user_id=current_user.user_id,
            username=username,
            recognition_type='drive_license',
            recognition_result=recognition_result,
            success_rate=success_rate,
            recognition_image=safe_ocr_text,
            device_info=device_info,
            ip_address=ip_address,
            recognition_data=json.dumps({
                'results_count': len(search_results),
                'results': [
                    {
                        'subject': r.get('subject', '')[:100],
                        'type_text': r.get('type_text', ''),
                        'optionA': r.get('optionA', '')
                    } for r in search_results[:3]
                ]
            }),
            photo_url=photo_url,
            tenant_id=tenant_id
        )

        db.session.add(record)

        if recognition_result == 'success':
            db_user = User.query.get(current_user.user_id)
            if db_user:
                db_user.usage_count -= 1

        db.session.commit()
        current_app.logger.info(f"异步保存成功 用户ID={current_user.user_id}, 租户ID={tenant_id}")

        for key in search_results:
            if key.get('noVerify') and not key.get('library_id') and not key.get('image'):
                print("Found noVerify:", key)
                key['image'] = photo_url
                save_result_to_json([key])

    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f"异步保存失败: {e}")
        current_app.logger.error("".join(traceback.format_exc()))
    finally:
        db.session.close()
        gc.collect()


# 其他可能需要修复的函数示例
def upload_file_to_cos(file_content, filename, tenant_id=None):
    """
    上传文件到COS的通用函数
    """
    from app.utils.cos_utils import get_cos_client
    
    try:
        # 动态获取COS配置
        cos_client, bucket, region = get_cos_client(tenant_id=tenant_id)
        
        # 执行上传
        ret = cos_client.put_object(
            Bucket=bucket,
            Body=io.BytesIO(file_content),
            Key=filename,
            EnableMD5=True
        )
        
        if ret.get('ETag'):
            return f"https://{bucket}.cos.{region}.myqcloud.com/{filename}"
        else:
            return None
            
    except Exception as e:
        from flask import current_app
        if current_app:
            current_app.logger.error(f"上传文件到COS失败: {str(e)}")
        return None


def delete_file_from_cos(filename, tenant_id=None):
    """
    从COS删除文件的通用函数
    """
    from app.utils.cos_utils import get_cos_client
    
    try:
        # 动态获取COS配置
        cos_client, bucket, region = get_cos_client(tenant_id=tenant_id)
        
        # 执行删除
        cos_client.delete_object(
            Bucket=bucket,
            Key=filename
        )
        return True
        
    except Exception as e:
        from flask import current_app
        if current_app:
            current_app.logger.error(f"从COS删除文件失败: {str(e)}")
        return False
